import React from 'react'
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, Radio, Modal, Message, Upload, DatePicker, InputNumber, Transfer } from 'antd';
import api from '../../../api/advPhoneType';
import { uuid } from "../../../utils";
const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
import moment from 'moment';


import AreaCascader from '../../Cascader/AreaCascader';
import PanelBox from '../../../components/PanelBox';
import { INTERFACE_CORE_URL } from '../../../api/config';
import SelectAdSales from '../SelectAdSale';


import './index.less'


class EditForm extends React.Component {
  state = {
    sumitLoad: false,
    children: [],
    photoUrl: '',
    userSession:'',

  };

  componentWillReceiveProps(nextProps) {
    if (this.props.clearForm != nextProps.clearForm && nextProps.clearForm == false) {
     
      this.setState({
        photoUrl: '',
        playStyle: '',
      })
      this.props.form.resetFields();
    }

  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {

        const photos = values.photos.file;
        if (typeof (photos) != "undefined") {
          const data = photos.response.data;
          values.photos = '["' + data.fullPath + '"]';
        }

        if (values.date.length > 0) {
          values.startDate = moment(values.date[0]).format("YYYY-MM-DD HH:mm:ss");
          values.endDate = moment(values.date[1]).format("YYYY-MM-DD HH:mm:ss");
        }
        delete values.date;
        console.log(values);
        this.setState({
          sumitLoad: true
        });
        if (values.id) {
          this.update(values);
        } else {
          this.add(values);
        }

      }
    });
  }
  update = (values) => {
    api.put('/advPhoneType/update', { ...values }).then((data) => {
      const result = data.data;
      if (result.code == 0) {
        Message.success('修改成功！');
        const { close, refeshData } = this.props;
        refeshData();
        close();
      } else {
        Message.error(result.message);
      }
      this.setState({
        sumitLoad: false
      });
    });
  }
  add = (values) => {
    delete values.id;
    api.post('/advPhoneType/add', { ...values }).then((data) => {
      const result = data.data;
      if (result.code == 0) {
       this.pay(result.data.id);
      } else {
        Message.error(result.message);
      }
      this.setState({
        sumitLoad: false
      });
    });
  }
  pay=(id) => {
    api.get('/adv/phoneType/pay',{params: {id:id}} ).then((data) => {
      const result = data.data;
      if(result.code == 0){
        Message.success('添加成功！');
        const { close, refeshData } = this.props;
        refeshData();
        close();
       }else{
        Message.error(result.message);
       }
    });
  }

  photos = {
    beforeUpload: (file) => {
     /* const isJPG = file.type === 'image/jpeg';
      if (!isJPG) {
        Message.error('您只能上传图片格式的文件!');
      }*/
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        Message.error('上传的图片必须小于等于2MB!');
      }
      return isLt2M;
    },
    handleImageChange: (info) => {
      if (info.file.status === 'done') {
        if (info.file.response) {
          this.setState({ photoUrl: info.file.response.data.fullPath + '?process=image/resize,width_150,height_150' })
        }
      }
    },
  }

  componentDidMount = () =>{
    let userSession =this.props.userSession;
    this.setState({
      userSession:userSession,
      });
  }

  styleTailFormItemLayout = {
    wrapperCol: {
      xs: {
        span: 14,
        offset: 0,
      },
      sm: {
        span: 14,
        offset: 6,
      },
    },
  };
  styleFormItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };


  render() {
    const { getFieldDecorator, resetFields } = this.props.form;
    const { close, refeshData, callbackParent } = this.props;
    callbackParent({
      resetFields: resetFields,
    });
    const record = this.props.rowRecord;
    let timeDef = "";
    if (record.timeDef) {
      timeDef = record.timeDef;
    }

    let imgStyle = {};
    if (record.photoUrl) {
      let url = "";
      if (this.state.photoUrl) {
        url = this.state.photoUrl;
      } else {
        url = record.photoUrl;
      }
      imgStyle = { background: "url(" + url + ") center center no-repeat" };
    }else{
      let url = this.state.photoUrl;
      imgStyle = { background: "url(" + url + ") center center no-repeat" };
    }

    const formItemLayout = this.styleFormItemLayout;
    const tailFormItemLayout = this.styleTailFormItemLayout;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>);
    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          {getFieldDecorator('id', {
            initialValue: record ? record.id : ''
          })(
            <Input type="hidden" />
            )}
          {getFieldDecorator('parentId', {
            initialValue: record ? record.parentId : ''
          })(
            <Input type="hidden" />
            )}
          <FormItem
            {...formItemLayout}
            label="所属父级"
          >
            {getFieldDecorator('parentName', {
              initialValue: (record && record.parentId) ? record.parentName : '最高'
            })(
              <Input disabled={true} />

              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="图片"
            hasFeedback
          >
            {getFieldDecorator('photos', {
              rules: [{
                required: true, message: '请上传图片!',
              }],
              initialValue: record ? record.photos : ''
            })(
              (!record || (record && record.examState == 1)) ?
              <Upload
                className="avatar-uploader"
                showUploadList={false}
                action={INTERFACE_CORE_URL + "/upload"}
                beforeUpload={this.photos.beforeUpload}
                onChange={this.photos.handleImageChange}
                accept="image/*"
                disabled={false}
              >
                {
                  record ?
                    (this.state.photoUrl || record.photos) ?
                      <div style={imgStyle} className="avatar" ></div> :
                      <Icon type="plus" className="avatar-uploader-trigger" />
                    :
                    (this.state.photoUrl) ?
                      <div style={imgStyle} className="avatar" ></div> :
                      <Icon type="plus" className="avatar-uploader-trigger" />
                }
              </Upload>:
              <Upload
                className="avatar-uploader"
                showUploadList={false}
                action={INTERFACE_CORE_URL + "/upload"}
                beforeUpload={this.photos.beforeUpload}
                onChange={this.photos.handleImageChange}
                disabled={true}
              >
                {
                  record ?
                    (this.state.photoUrl || record.photos) ?
                      <div style={imgStyle} className="avatar" ></div> :
                      <Icon type="plus" className="avatar-uploader-trigger" />
                    :
                    (this.state.photoUrl) ?
                      <div style={imgStyle} className="avatar" ></div> :
                      <Icon type="plus" className="avatar-uploader-trigger" />
                }
              </Upload>
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="标题"
            hasFeedback
          >
            {getFieldDecorator('title', {
              rules: [{ required: true, message: '标题不能为空!' }],
              initialValue: record ? record.title : ''
            })(
              (!record || (record && record.examState == 1)) ? <Input placeholder="请输入标题" disabled={false} /> : <Input placeholder="请输入广告标题" disabled={true} />

              )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label="内容"
            hasFeedback
          >
            {getFieldDecorator('content', {
              initialValue: record ? record.content : ''
            })(
              (!record || (record && record.examState == 1)) ? <TextArea rows={4} placeholder="请输入内容" disabled={false} /> : <TextArea rows={4} placeholder="请输入广告内容" disabled={true} />
              )}
          </FormItem>
          
          <FormItem
            {...formItemLayout}
            label="起止时间"
            hasFeedback
          >
            {getFieldDecorator('date', {
              rules: [{ required: true, message: '起止时间不能为空!' }],
              initialValue: timeDef
            })(
              (!record || (record && record.examState == 1)) ? <RangePicker style={{width:'400px'}} format="YYYY-MM-DD HH:mm:ss" disabled={false} /> : <RangePicker style={{width:'400px'}}  format="YYYY-MM-DD HH:mm:ss" disabled={true} />
              )}
          </FormItem>
          <FormItem
              {...formItemLayout}
              label="显示位置"
            >
                {getFieldDecorator('showPosition', {
                    rules: [{ required: true, message: '显示位置不能为空!' }],
                    initialValue:record ? record.showPosition  : 1
                  })(
                  (!record || (record && record.examState == 1)) ? 
                  <RadioGroup name="showPosition" disabled={false}>
                    <Radio value={1}>上</Radio>
                    <Radio value={2}>下</Radio>
                  </RadioGroup>:
                  <RadioGroup name="showPosition" disabled={true}>
                    <Radio value={1}>上</Radio>
                    <Radio value={2}>下</Radio>
                  </RadioGroup>

              )}
          </FormItem>
          <FormItem
              {...formItemLayout}
              label="排序"
              extra="用于app展示"
            >
                {getFieldDecorator('sort', {
                    rules: [{ required: true, message: '排序不能为空!' }],
                    initialValue:record ? record.sort : ''
                  })(
                  
                   (!record || (record && record.examState == 1)) ? 
                  <InputNumber disabled={false}/>:<InputNumber disabled={true}/>
                 
                 
              )}
          </FormItem>
          <FormItem
              {...formItemLayout}
              label="URL"
            >
                {getFieldDecorator('url', {
                    initialValue:record ? record.url   : ''
                  })(

                    (!record || (record && record.examState == 1)) ?  <Input placeholder="点击跳转的地址" disabled={false} /> :  <Input placeholder="点击跳转的地址" disabled={true} />
              )}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
          {(!record || (record && record.examState == 1)) ?<Button type="primary" htmlType="submit" size="large" style={{ marginRight: '10px' }}>提交</Button>:''}
            <Button onClick={close}>取消</Button>

          </FormItem>
        </Form>

      </div>
    );
  }
}

const WrappedEditForm = Form.create()(EditForm);
export default WrappedEditForm
